const http = require("http");
const url = require("url")
const server = http.createServer();
const { httpFileRequest, httpRequest, readFile, writeFile } = require('./utils/httpRequest')
const message =require("./dao/message")



server.listen(3001, function () {
    console.log("留言板服务已启动");
})

server.on("request", function (request, response) {
    const { pathname, query } = url.parse(request.url, true)
    
    if (request.url === "/") {

        message.list().then(res => {
            httpFileRequest("./views/index.html", response, { list: res })

        })

    } else if (request.url === "/add") {
        httpRequest("./views/add.html", response)
    } else if (pathname === "/save") {
        message.
        readFile("./data.json").then(res => {
            const list = JSON.parse(res);
            list.push(query);
            return list;
        }).then((list) => {
            writeFile("./data.json", JSON.stringify(list)).then(res => {
                response.statusCode = 302;
                response.setHeader("location", "/");
                response.end()
            })
        })
    } else if (pathname.startsWith('/node_modules')) {
        httpRequest("." + pathname, response)
    } else {
        httpRequest("./views/error.html", response)
    }
})